package com.hui.config.security.web.access.intercept;

import com.hui.config.security.web.access.UrlConfigAttribute;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 默认:可以通过url得到角色名称,此处用户获取
 * 权限资源 SecurityMetadataSource
 * 调用Security元数据源
 */
public class MyFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     *
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // object 是一个request，被用户请求的request。
        final HttpServletRequest request = ((FilterInvocation) object).getRequest();
        Set<ConfigAttribute> allAttributes = new HashSet<>();
        ConfigAttribute configAttribute = new UrlConfigAttribute(request);
        allAttributes.add(configAttribute);
        return allAttributes;
//        FilterInvocation fi = (FilterInvocation) object;
//        String url = fi.getRequestUrl();
////        String httpMethod = fi.getRequest().getMethod();
//        for (Map.Entry<String, String> entry : urlRoleMap.entrySet()) {
//            if (antPathMatcher.match(entry.getKey(), url)) {
//                return SecurityConfig.createList(entry.getValue());
//            }
//        }
        //没有匹配到,默认是要登录才能访问
//        return SecurityConfig.createList("ROLE_USER");
//        return null;// 如果返回为null则说明此url地址不需要相应的角色就可以访问, 这样Security会放行
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
